package com.org.daniel.framework.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author Daniel
 */
@Configuration
@MapperScan(basePackages = "com.org.daniel.mapper.manager", sqlSessionTemplateRef = "managerSqlSessionTemplate")
public class DataSourceConfigManager {

	@Bean(name = "managerDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.manager")
	public DataSource managerDataSource(){
		return DruidDataSourceBuilder.create().build();
	}

	@Bean(name = "managerMybatisConfig")
	@ConfigurationProperties(prefix = "mybatis.configuration.manager")
	public org.apache.ibatis.session.Configuration managerConfig(){
		return new org.apache.ibatis.session.Configuration();
	}

	@Bean(name = "managerSqlSessionFactory")
	public SqlSessionFactory managerSqlSessionFactory(@Qualifier("managerDataSource")DataSource dataSource,
	                                                  @Qualifier("managerMybatisConfig") org.apache.ibatis.session.Configuration managerConfig)
			throws Exception{
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setConfiguration(managerConfig);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/manager/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "managerTransactionManager")
	public DataSourceTransactionManager managerTransactionManager(@Qualifier("managerDataSource")DataSource dataSource){
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "managerSqlSessionTemplate")
	public SqlSessionTemplate managerSqlSessionTemplate(@Qualifier("managerSqlSessionFactory")SqlSessionFactory sqlSessionFactory) throws Exception{
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
